//
//  MyCollectionViewController.m
//  EnvironmentalProtection
//
//  Created by HCreater on 2018/11/7.
//  Copyright © 2018年 HCreater. All rights reserved.
//

#import "MyCollectionViewController.h"

#import "StwxDetailViewController.h"
#import "DocumentDetailViewController.h"

#import "CommonNewsItemCell.h"

#import "CollectionListData.h"

@interface MyCollectionViewController ()

/// 模型视图
@property (nonatomic, readonly, strong) MyCollectionViewModel* viewModel;

// UI

//IBOutlet
@property (nonatomic, weak) IBOutlet UITableView* currentTableView;

@property (nonatomic, strong) NSIndexPath* _editingIndexPath;

@end

@implementation MyCollectionViewController
@dynamic viewModel;

- (instancetype)initWithViewModel:(SUViewModel2 *)viewModel
{
    self = [super initWithViewModel:viewModel];
    if (self)
    {
        [self initData];
        [self initLoadForRAC];
        [self initUI];
    }
    return self;
}

- (void)viewDidLoad
{
    [super viewDidLoad];
    // Do any additional setup after loading the view from its nib.
    
    // hide sys navBar
    self.fd_prefersNavigationBarHidden = NO;
    // 去掉侧滑pop手势
    self.fd_interactivePopDisabled = YES;
    // create subViews
    [self _setupSubViews];
    // deal action
    [self _dealAction];
    /// tableView rigister  cell
    [self.tableView mh_registerNibCell:[CommonNewsItemCell class]];
}

- (void)viewDidLayoutSubviews
{
    [super viewDidLayoutSubviews];
}

- (void)didReceiveMemoryWarning
{
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}

- (void)initData
{
    
}

- (void)initLoadForRAC
{
    @weakify(self)
    [[self rac_signalForSelector:@selector(viewDidLoad)] subscribeNext:^(id x)
     {
         @strongify(self)
         
     }];
}

- (void)initUI
{
    @weakify(self);
    
}

#pragma mark - Override
- (void)bindViewModel
{
    [super bindViewModel];
    
    @weakify(self)
    
    RACSignal* willAppearSignal = [[self rac_signalForSelector:@selector(viewWillAppear:)] replay];
    RACSignal* didAppearSignal = [[self rac_signalForSelector:@selector(viewDidAppear:)] replay];
    RACSignal* viewDidLayoutSVSignal = [[self rac_signalForSelector:@selector(viewDidLayoutSubviews)] replay];
    
    [willAppearSignal subscribeNext:^(id x) {
        @strongify(self)
        
    }];
    
    [didAppearSignal subscribeNext:^(id x) {
        @strongify(self)
        
        // ScrollView 内容 未能在此时才约束
        
        //Request
    }];
    
    [[self rac_signalForSelector:@selector(viewWillDisappear:)] subscribeNext:^(id x)
     {
         @strongify(self)
         
     }];
    
    [[[viewDidLayoutSVSignal take:1] deliverOnMainThread] subscribeNext:^(id x)
     {
         @strongify(self)
         
         //重置 更新 frame
         [self _setupAllView];
     }];
    
#pragma mark -- bindViewModel
    
    UserManagerV2* um = [UserManagerV2 sharedUserManagerV2];
    
    [[self.currentTableView rac_signalForSelector:@selector(layoutSubviews)] subscribeNext:^(id x)
    {
        @strongify(self);
        
        [self _setupTableViewDeleteCell];
    }];
    
    self.viewModel.didSelectCommand = self.viewModel.selectCmd;
    
    [[self.viewModel.selectCmd.executionSignals.switchToLatest deliverOnMainThread] subscribeNext:^(id x) {
        @strongify(self)
        
        [self _push2StwxDetailVCByArticleID:x];
    }];
    
    /// 取消收藏
    [[self.viewModel.unCollectionCmd.executionSignals.switchToLatest deliverOnMainThread]
     subscribeNext:^(id x) {
         @strongify(self);
         [MBProgressHUD mh_hideHUD];
         
         [MBProgressHUD mh_showTips:x];
     }];
    
    /// 错误信息
    [self.viewModel.unCollectionCmd.errors subscribeNext:^(NSError *error)
     {
         [MBProgressHUD mh_hideHUD];
         
         /// 处理验证错误的error
         if ([error.domain isEqualToString:SUCommandErrorDomain])
         {
             [MBProgressHUD mh_showTips:error.userInfo[SUCommandErrorUserInfoKey]];
             return ;
         }
         [MBProgressHUD mh_showErrorTips:error];
     }];
}

- (UITableView*)customTableView
{
    return self.currentTableView;
}

#pragma mark - 更新初始化 操作
- (void)_setupSubViews
{
    
}

- (void)_setupAllView
{
    @weakify(self);
    
    UserManagerV2* um = [UserManagerV2 sharedUserManagerV2];
}

- (void)_setupTableViewDeleteCell
{
    if (MHIOS11)
    {
        for (UIView *subview in self.tableView.subviews)
        {
            if([subview isKindOfClass:NSClassFromString(@"UISwipeActionPullView")])
            {
                UIView *swipeActionPullView = subview;
                //1.0修改背景颜色
                swipeActionPullView.backgroundColor = UIColorHex(#f4f4f4);
                //1.1修改背景圆角
                //                swipeActionPullView.layer.cornerRadius = 5.f;
                //                swipeActionPullView.layer.masksToBounds = YES;
                
                //2.0修改按钮-颜色
                UIButton *swipeActionStandardBtn = subview.subviews[0];
                if ([swipeActionStandardBtn isKindOfClass:NSClassFromString(@"UISwipeActionStandardButton")]) {
                    
                    CGFloat swipeActionStandardBtnOX = swipeActionStandardBtn.frame.origin.x + 8;
                    CGFloat swipeActionStandardBtnW = subview.frame.size.width - 16;
                    swipeActionStandardBtn.frame = CGRectMake(swipeActionStandardBtnOX, (subview.frame.size.height - swipeActionStandardBtnW)/2.0f, swipeActionStandardBtnW, swipeActionStandardBtnW);
                    //2.1修改按钮背景色
                    swipeActionStandardBtn.backgroundColor = UIColorHex(#FFFFFF);
                    //2.2修改按钮背景圆角
                    swipeActionStandardBtn.layer.cornerRadius = swipeActionStandardBtnW/2.0f;
                    swipeActionStandardBtn.layer.masksToBounds = YES;
                    
                    [swipeActionStandardBtn setBackgroundImage:MHImageNamed(@"icon_lajitong") forState:UIControlStateNormal];
                }
            }
        }
    }
    else
    {
        // iOS 8-10层级 (Xcode 8编译): UITableView -> UITableViewCell -> UITableViewCellDeleteConfirmationView
        CommonNewsItemCell *tableCell = [self.tableView cellForRowAtIndexPath:self._editingIndexPath];
        for (UIView *subview in tableCell.subviews)
        {
            NSLog(@"subview%@-----%zd",subview,subview.subviews.count);
            
            if ([subview isKindOfClass:NSClassFromString(@"UITableViewCellDeleteConfirmationView")] && [subview.subviews count] >= 1)
            {
                UIButton *deleteButton = subview.subviews[0];
                [deleteButton setBackgroundColor:UIColorHex(#FFFFFF)];
                [deleteButton setBackgroundImage:MHImageNamed(@"icon_lajitong") forState:UIControlStateNormal];
            }
        }
    }
}

#pragma mark - 事件处理
/// 事件处理
- (void)_dealAction
{
    @weakify(self);
    
}

#pragma mark - Delegate 一些无法用RAC实现
// UIScrollViewDelegate
- (void)scrollViewDidScroll:(UIScrollView *)scrollView
{
    
}

//// 下拉刷新
- (void)tableViewDidTriggerHeaderRefresh{
    /// 先调用父类的加载数据
    [super tableViewDidTriggerHeaderRefresh];
}
/// config  cell
- (UITableViewCell *)tableView:(UITableView *)tableView dequeueReusableCellWithIdentifier:(NSString *)identifier forIndexPath:(NSIndexPath *)indexPath
{
    return [tableView dequeueReusableCellWithIdentifier:NSStringFromClass([CommonNewsItemCell class])];
}

/// config  data
- (void)configureCell:(CommonNewsItemCell *)cell atIndexPath:(NSIndexPath *)indexPath withObject:(CommonNewsItemViewModel *)object
{
    /// config data (PS：由于MVVM主要是View与数据之间的绑定，但是跟 setViewModel: 差不多啦)
    [cell bindViewModel:object];
}

/// 文本内容区域
//- (UIEdgeInsets)contentInset
//{
//    return UIEdgeInsetsZero;
//}

#pragma mark - UITableViewDelegate
- (CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath{
    /// 由于使用系统的autoLayout来计算cell的高度，每次滚动时都要重新计算cell的布局以此来获得cell的高度 这样一来性能不好
    /// 所以笔者采用实现计算好的cell的高度
    
    return [self.viewModel.dataSource[indexPath.row] cellHeight];
}

////////////////// 以下为UI代码，不必过多关注 ///////////////////
#pragma mark - UITableViewDelegate
- (CGFloat)tableView:(UITableView *)tableView heightForFooterInSection:(NSInteger)section
{
    return .0001f;
}

- (CGFloat)tableView:(UITableView *)tableView heightForHeaderInSection:(NSInteger)section
{
    /// FIXED : when data is empty ，the backgroundColor is exist
    return .0001f;
}

- (BOOL)tableView:(UITableView *)tableView canEditRowAtIndexPath:(NSIndexPath *)indexPath
{
    return YES;
}

- (void)tableView:(UITableView *)tableView willBeginEditingRowAtIndexPath:(NSIndexPath *)indexPath
{
    self._editingIndexPath = indexPath;
    [self.view setNeedsLayout];   // 触发-(void)viewDidLayoutSubviews
}
- (void)tableView:(UITableView *)tableView didEndEditingRowAtIndexPath:(NSIndexPath *)indexPath
{
    self._editingIndexPath = nil;
}

// 定义编辑样式
- (UITableViewCellEditingStyle)tableView:(UITableView *)tableView editingStyleForRowAtIndexPath:(NSIndexPath *)indexPath
{
    return UITableViewCellEditingStyleDelete;
}

// 进入编辑模式，按下出现的编辑按钮后,进行删除操作
- (void)tableView:(UITableView *)tableView commitEditingStyle:(UITableViewCellEditingStyle)editingStyle forRowAtIndexPath:(NSIndexPath *)indexPath
{
    if (editingStyle == UITableViewCellEditingStyleDelete)
    {
        [self.viewModel.unCollectionCmd execute:indexPath];
    }
}

// 修改编辑按钮文字
- (NSString *)tableView:(UITableView *)tableView titleForDeleteConfirmationButtonForRowAtIndexPath:(NSIndexPath *)indexPath
{
    return @"       ";
}

#pragma mark-代理方法
// 设立实现代理，注意要返回UIModalPresentationNone
- (UIModalPresentationStyle)adaptivePresentationStyleForPresentationController:(UIPresentationController *)controller
{
    return UIModalPresentationNone;
}

#pragma mark - 功能

#pragma mark - 跳转
- (void)_push2StwxDetailVCByArticleID:(CollectionListData*)clistData;
{
    NSString* cateID = clistData.articleInfo.cateID;
    NSString* articleID = clistData.articleInfo.articleID;
    
    if ([clistData.type isEqualToString:@"1"])
    {
        StwxDetailViewModel* vm = [[StwxDetailViewModel alloc] initWithParams:@{}];
        //    [vm initStwxDetail:stwxDetailIVM];
        vm.isHaveDetailCtrl = [cateID isEqualToString:@"59"];
        vm.articleID = articleID;
        StwxDetailViewController* vc = [[StwxDetailViewController alloc] initWithViewModel:vm];
        UIViewController* showVC = [UIViewController getCurrentVC];
        
        UINavigationController* navc = showVC.navigationController;
        [navc pushViewController:vc animated:YES];
    }
    else
    {
        DocumentDetailViewModel* vm = [[DocumentDetailViewModel alloc] initWithParams:@{}];
        //    [vm initStwxDetail:stwxDetailIVM];
        vm.articleID = articleID;
        DocumentDetailViewController* vc = [[DocumentDetailViewController alloc] initWithViewModel:vm];
        UIViewController* showVC = [UIViewController getCurrentVC];
        
        UINavigationController* navc = showVC.navigationController;
        [navc pushViewController:vc animated:YES];
    }
}

@end
